package com.ruoyi.file.service.impl;

import com.ruoyi.file.config.MinioConfig;
import com.ruoyi.file.domain.FileType;
import com.ruoyi.file.domain.SysFile;
import com.ruoyi.file.utils.FileUploadUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Minio 文件存储
 * 
 * @author ruoyi
 */
@Primary
@Service
public class MinioSysFileServiceImpl extends AbstractIFileService
{
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;

    @Override
    public FileType fileType() {
        return FileType.MINIO;
    }

    @Override
    protected boolean deleteFile(SysFile fileInfo) {
        try {
            RemoveObjectArgs args = RemoveObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(fileInfo.getName())
                    .build();
            // 删除`my-bucketname`存储桶，注意，只有存储桶为空时才能删除成功。
            client.removeObject(args);
            System.out.println("FIle is removed successfully");
            List<SysFile> sysFiles = sysFileMapper.selectSysFileList(fileInfo);
            if (sysFiles.size() > 0) {
                sysFileMapper.deleteSysFileById(sysFiles.get(0).getId());
            }
        } catch(MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            System.out.println("Error occurred: " + e);
        }
        return false;
    }

    /**
     * 本地文件上传接口
     * 
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    protected void uploadFile(MultipartFile file, SysFile fileInfo) throws Exception {

        String fileName = FileUploadUtils.extractFilename(file);
        fileInfo.setPath(fileName);

        String[] strings = fileName.split("/");
        fileInfo.setName(strings[strings.length -1]);

        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileInfo.getPath())
                .stream(file.getInputStream(), fileInfo.getSize(), -1)
                .contentType(fileInfo.getContentType())
                .build();
        client.putObject(args);
        fileInfo.setSource(fileType().name());// 设置文件来源

        String url = minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
        fileInfo.setUrl( url);
    }

}
